const app = getApp()
const db = wx.cloud.database()
const util = require('../../utils/util')
const _ = db.command
Page({
  data: {
    PageCur: 'index',
    userInfo:app.globalData.userInfo ,
    auth:false,
    newNum:'',
    newMessages:'测试'
  },
  NavChange(e) {
    // const db = wx.cloud.database()
    // db.collection('yw_commodity').where({}).get({
    //   success: function(res) {
    //   app.globalData.commodity=res.data
    //  }
    // })
    
    if(e.currentTarget.dataset.url=='gc'||app.globalData.auth){
      this.setData({
        PageCur: e.currentTarget.dataset.url
      })
    }else{
      wx.cloud.callFunction({
        name:'getOpenId'
      }).then(res=>{
        console.log(res)
        let openid = res.result
        this.queryAuthByOpenid(openid)
      })
    }
  },
  onShareAppMessage() {
    return {
      title: 'ColorUI-高颜值的小程序UI组件库',
      imageUrl: '/images/share.jpg',
      path: '/pages/index/index'
    }
  },
  ls(){
wx.navigateTo({
  url: '../issue/issue',
})
  },
  onLoad:function(){
     wx.getStorage({
      key: 'user_auth',
      success:res=>{
        this.setData({
            auth: res.data
        })
      },
      fail:res=>{
        console.log('还没有')
      },
      complete:res=>{
          if(this.data.auth){
            this.getUserData()
          }else{
            wx.cloud.callFunction({
              name:'getOpenId'
            }).then(res=>{
              console.log(res)
              let openid = res.result
              this.queryAuthByOpenid(openid)
            })
          }
      }
    })
    

    // let _ = db.command
    // db.collection('yw_exchange').where({chatId:'b'}).update({
    //   data:{
    //     msg:_.push({status:'userl',message:"新消息3",date:'2021-4-25 08:43:08'})
    //   }
    // })
    // console.log(4)
  },
// 2. 构造查询语句
// collection 方法获取一个集合的引用
// where 方法传入一个对象，数据库返回集合中字段等于指定值的 JSON 文档。API 也支持高级的查询条件（比如大于、小于、in 等），具体见文档查看支持列表
// get 方法会触发网络请求，往数据库取数据

// 授权
  authorization(){
    wx.cloud.callFunction({
      name:'getOpenId'
    }).then(res=>{
      console.log(res)
      let openid = res.result
      this.queryAuthByOpenid(openid)
    })
  },
// 获取用户数据
  getUserData(){
    wx.showLoading({
      title: '数据加载中',
    })
    wx.cloud.callFunction({
      name:'login', 
    }).then(res=>{
      console.log(res)
        app.globalData.userInfo=res.result.data[0]
        this.setData({
          userInfo:app.globalData.userInfo
        })
        this.getMessages()
        // 监听新消息
        db.collection('yw_exchange').where({openid:this.data.userInfo._openid}).watch({
            onChange:e=>{
              var newN =''
              e.type=='init'?wx.hideLoading():''
              try{newN = e.docs.reduce((a,b)=>{
                return a.msg.length+b.msg.length
              })}
              catch(err){
                  console.log(err)
              }
              this.setData({
                newNum:newN,
                newMessages:e.docs
              })
            },
            onError:error=>{
              console.log(error)
            }
      })

    })
  },
  //获取聊天记录
  getMessages(){
    app.globalData.auth=true
    db.collection('yw_exchange').where({openid:this.data.userInfo._openid}).get().then(res=>{
      app.globalData.newMessages=res.data[0]
    })
  },
  // 用户否授权
  queryAuthByOpenid(openid){
        wx.showModal({
          confirmColor: 'confirmColor',
          confirmText: '授权登录',
          showCancel:false,
          content: '易宝小程序需要您授权才能提供更好的服务哦',
          title: '登录提示',
          complete: (res) => {
            wx.getUserProfile({
              desc:'仅作展示',
              success:res=>{
                console.log(res) 
                this.updateUserAuth(res.userInfo)
              },
              fail:res=>{
                wx.showToast({
                  title: '您已拒绝授权',
                  icon:'error'
                })
              }
            })
          },
        })
     
  },
  // 更新用户授权
  updateUserAuth(userInfo){
      wx.cloud.callFunction({
        name:'getOpenId',
        complete:res=>{
          let openid  = res.result
          db.collection("yw_user").where({_openid:openid}).get({
            success:res=>{
              console.log(res)
                if(res.data.length==1){
                  // this.deleteAndSaveUser(res.data[0]._id,userInfo)
                  // db.collection('yw_user').where({openid:openid}).update({
                  //   auth:true
                  // }).then((res)=>{

                  // })
                  wx.setStorage({
                    data: true,
                    key: 'user_auth',
                  })
                  this.setData({
                    auth:'true'
                  })
                  this.getUserData()
                }else{
                  this.saveUser(userInfo)
                }
            },
            fail(res){
              console.log(res)
            },complete(){
            }
          })
        }
      })
  },
  // 保存用户
  saveUser(userInfo){
    db.collection('yw_user').add({
      data:{
        auth:true,
        avatar: userInfo.avatarUrl,
        nickname: userInfo.nickName,
        gender:userInfo.gender==1?'男':'女',
        country:userInfo.country,
        provice:userInfo.provice,
        city:userInfo.city,
        barter_enter:0,
        bater_quantity:0,
        depatment:"计算机与设计学院",
        grade:"19级",
        createtime:util.formatTime(new Date()),
        specialty:'软件技术',
        chatName:userInfo.nickName[0]+"同学"
      },
      success:res=>{
      console.log("成功了")
      this.getUserData()
      wx.setStorage({
        data: true,
        key: 'user_auth',
      })
      this.setData({
        auth:'true'
      })
      },
      fail:res=>{
        console.log(res)
      }
    }).then(res=>{
      this.getUserData()
      wx.setStorage({
        data: true,
        key: 'user_auth',
      })
      this.setData({
        auth:'true'
      })
    })
    
  },
  jump_to(e){
    if(e.currentTarget.dataset.url=='music_page'||app.globalData.auth){
      wx.navigateTo({
        url: '../'+e.currentTarget.dataset.url+'/'+e.currentTarget.dataset.url,
      })
    }else{
    }
  },
})